/*******************************************************************************
 * Copyright (c) 2009-2011 ETCORE Labs. All rights reserved. 
 * 
 * This software is the confidential and proprietary information of ETCORE Labs.
 * You shall not disclose such confidential information and shall use it
 * only in accordance with the terms of the license agreement you entered into
 * with ETCORE Labs. 
 * 
 * Support can be obtained from support forums at:  http://www.etcore.com/
 * /
 *******************************************************************************/
package etcore.webapp.grouptalk.admin.action;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;

import etcore.webapp.grouptalk.common.action.AbstractAction;
import etcore.webapp.grouptalk.common.config.Config;
import etcore.webapp.grouptalk.common.config.MessageNamespaces;
import etcore.webapp.grouptalk.common.config.Messages;
import etcore.webapp.grouptalk.common.config.PageConstants;
import etcore.webapp.grouptalk.common.dao.TopicDAO;
import etcore.webapp.grouptalk.common.object.Group;
import etcore.webapp.grouptalk.common.object.Topic;
import etcore.webapp.grouptalk.common.service.GroupService;
import etcore.webapp.grouptalk.user.object.Member;
import etcore.webapp.grouptalk.user.object.User;
import etcore.webapp.grouptalk.user.service.MemberService;
import etcore.webapp.grouptalk.util.DateUtil;
import etcore.webapp.grouptalk.util.Symbols;

/**
 * This action validates the request and executes the command of adding a
 * group,then set the corresponding attributes for output
 * 
 * @author ETCORE GroupTalk Developers
 * 
 */
public class AddGroupAction extends AbstractAction {

	private static final long serialVersionUID = 1016793864856278227L;
	public static final int ACCESS_ALLOWED = 1;
	public static final int ACCESS_ERROR = 0;

	public static final String CMD_VALUE = "addGroup";
	public static final String ONE = "1";
	public static final String TWO = "2";
	public static final String ZERO = "0";
	public static final String TEN_THOUSAND = "10000";
	public static final String OWNER = "owner";

	@Override
	public int validate(HttpServletRequest request, HttpServletResponse response) {
		// TODO Auto-generated method stub

		boolean isAdmin = (Boolean) request.getAttribute(PageConstants.ISADMIN);

		if (isAdmin) {
			return ACCESS_ALLOWED;
		}
		return ACCESS_ERROR;
	}

	@Override
	public String getForward(HttpServletRequest request, int validationResult) {
		// TODO Auto-generated method stub
		if (validationResult == ACCESS_ALLOWED)
			return PageConstants.PAGE_PATH_ADDGROUP;
		return PageConstants.ACTION_PATH_ERROR;
	}

	@Override
	public String getRedirect(HttpServletRequest request, int validationResult) {
		// TODO Auto-generated method stub

		return null;
	}

	@Override
	public void execute(int validationResult, HttpServletRequest request,
			HttpServletResponse response) {
		// TODO Auto-generated method stub
		if (ACCESS_ALLOWED == validationResult) {

			addGroup(request);

		}
	}

	@SuppressWarnings("rawtypes")
	private void addGroup(HttpServletRequest request) {
		String cmd = request.getParameter(PageConstants.CMD);

		if (CMD_VALUE.equals(cmd)) {
			GroupService groupService = new GroupService();
			Group group = new Group();
			MemberService memberService = new MemberService();
			HttpSession session = request.getSession(true);
			User user = (User) session.getAttribute(Messages.SESSION_USER);
			String lang = (String) session.getAttribute(Messages.LANG);
			String ppp1 = this.getServletConfig().getServletContext()
					.getRealPath("WEB-INF");
			String ppp = ppp1.substring(0, ppp1.indexOf("WEB-INF"));
			String uploadPath = ppp + "group/upload/images";
			String tempPath = ppp + "group/upload/temp/";
			String info = null;
			String pic = "/group/images/root.gif";
			String name = null;
			String notice = Symbols.BLANK;
			String open = ONE;
			String up = TEN_THOUSAND;
			String func = ZERO;
			String nav = ZERO;
			String local = ONE;
			String en = ONE;
			String msg = null;

			try {
				if (!new File(uploadPath).isDirectory())
					new File(uploadPath).mkdirs();
				if (!new File(tempPath).isDirectory())
					new File(tempPath).mkdirs();
				DiskFileUpload diskFileUpload = new DiskFileUpload();

				diskFileUpload.setSizeMax(200 * 1024);

				diskFileUpload.setSizeThreshold(4096);

				diskFileUpload.setRepositoryPath(tempPath);

				List fileItems = diskFileUpload.parseRequest(request);
				Iterator fileItemIterator = fileItems.iterator();

				while (fileItemIterator.hasNext()) {
					FileItem fileItem = (FileItem) fileItemIterator.next();

					if (fileItem.isFormField()) {
						if (fileItem.getFieldName().equals(PageConstants.NAME)) {
							name = fileItem
									.getString(PageConstants.ENCODING_UTF8);
							if (!name.equals(group.getName())
									&& groupService.isUsedName(name) == 1) {

								if (lang != null
										&& lang.equals(Messages.LANG_EN)) {
									msg = Messages
											.getELabel(Messages.MSG_NAME_CONFLICT);
								} else {
									msg = Messages
											.getLabel(Messages.MSG_NAME_CONFLICT);
								}

								request.setAttribute(PageConstants.MSG, msg);
								return;

							}
						}

						else if (fileItem.getFieldName().equals(
								PageConstants.INFO))
							info = fileItem
									.getString(PageConstants.ENCODING_UTF8);
						else if (fileItem.getFieldName().equals(
								PageConstants.OPEN)){
							open = fileItem.getString();
							if ("11".equals(open)) {
								open = PageConstants.ONE;
								nav = PageConstants.ONE;
							} else if ("22".equals(open)) {
								open = "2";
								nav = PageConstants.ONE;
							}
						}
						else if (fileItem.getFieldName().equals(
								PageConstants.UP))
							up = fileItem.getString();
						else if (fileItem.getFieldName().equals(
								PageConstants.FUNC))
							func = fileItem.getString();

						else if (fileItem.getFieldName().equals(
								Messages.LANG_LOCAL))
							local = fileItem.getString();
						else if (fileItem.getFieldName().equals(
								Messages.LANG_EN))
							en = fileItem.getString();
					 
					}
					if (!fileItem.isFormField()) {
						int fileError = 0;
						String fileName = fileItem.getName();
						if (fileName != null)
							fileName = fileName.substring(fileName
									.lastIndexOf("\\") + 1);
						if (fileName == null || fileName.equals(Symbols.BLANK))
							fileError = 1;
						String suffixName = null;
						if (fileError != 1) {
							suffixName = Symbols.DOT
									+ fileName.substring(fileName
											.lastIndexOf(Symbols.DOT) + 1);

							fileName = new java.sql.Timestamp(
									System.currentTimeMillis()).toString()
									.substring(0, 13)
									+ new java.sql.Timestamp(
											System.currentTimeMillis())
											.toString().substring(14, 16)
									+ new java.sql.Timestamp(
											System.currentTimeMillis())
											.toString().substring(17, 19)
									+ suffixName;

							if (suffixName.equals(".JPG")
									|| suffixName.equals(".jpg")
									|| suffixName.equals(".GIF")
									|| suffixName.equals(".gif")
									|| suffixName.equals(".BMP")
									|| suffixName.equals(".bmp")) {
								pic = "/group/upload/images/" + fileName;

								File savedFile = new File(uploadPath, fileName); //

								fileItem.write(savedFile);//
							}

						}

					}
				}

				group.setName(name);
				group.setInfo(info);
				group.setPic(pic);
				group.setNotice(notice);
				group.setOpen(new Integer(open));
				group.setUp(new Integer(up));
				group.setFunc(new Integer(func));
				group.setLocal(new Integer(local));
				group.setEn(new Integer(en));
				if (ONE.equals(open) || TWO.equals(open))
					group.setNav(new Integer(nav));
				group.setTime(DateUtil.getTime(Config.getProperty(Config.HOURS_DIFFERENCE)));

				groupService.save(group);

				TopicDAO gtdao = new TopicDAO();
				Topic topic = new Topic();
				if (group.getLocal() == 1)
					topic.setName(Messages.getLabel(Messages.DEFAULT_TOPIC));
				else
					topic.setName(Messages.getELabel(Messages.DEFAULT_TOPIC));
				topic.setGid(group.getId());
				topic.setTime(DateUtil.getTime(Config.getProperty(Config.HOURS_DIFFERENCE)));

				topic.setUserName(user.getUserName());
				topic.setParent(new Integer(0));
				gtdao.save(topic);

				Member member = new Member();
				member.setGid(group.getId());
				member.setUserName(user.getUserName());
				member.setMytype(OWNER);
				member.setApp(new Integer(0));

				member.setMainnum(new Integer(0));
				member.setCreateTime(DateUtil.getTime(Config.getProperty(Config.HOURS_DIFFERENCE)));
				member.setTotalnum(new Integer(0));
				member.setLastTime(DateUtil.getTime(Config.getProperty(Config.HOURS_DIFFERENCE)));
				member.setEnergy(new Integer(0));
				memberService.save(member);

				if (lang != null && lang.equals(Messages.LANG_EN)) {
					msg = Messages.getELabel(Messages.MSG_SUCCESS);
				} else {
					msg = Messages.getLabel(Messages.MSG_SUCCESS);
				}
				request.setAttribute(PageConstants.MSG, msg);

			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public boolean isForward(int validationResult) {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	public boolean enablePostLoad() {
		// TODO Auto-generated method stub
		return true;
	}

	/* (non-Javadoc)
	 * @see etcore.webapp.grouptalk.controller.action.AbstractAction#buildSelfContextAndAttributes(int, javax.servlet.http.HttpServletRequest)
	 */
	@Override
	public List<String> getNamespacesOfMessages(HttpServletRequest request) {
		// TODO Auto-generated method stub
		List<String> namespaces = new ArrayList<String>();
		namespaces.add(MessageNamespaces.GROUP_ADMIN);
		return namespaces;	
	}

}
